package com.dxt.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * 共用方法
 * 重写Object的toString方法
 * return 对象的json串
 */
public class MyObjectUtil {

    private static final Logger logger = LoggerFactory.getLogger(MyObjectUtil.class);

    public static String show(Object object) {
        try {
            Class cls = object.getClass();
            StringBuffer buf = new StringBuffer();
            buf.append("{");
            Field[] fields = cls.getDeclaredFields();
            for(int i = 0; i < fields.length; i++){
                Field f = fields[i];
                f.setAccessible(true);
                buf.append(f.getName()).append(":").append("'").append(f.get(object)).append("'");
                if (i != fields.length-1)
                    buf.append(", ");
                else
                    buf.append("}");
            }
            return buf.toString();
        } catch (IllegalAccessException e) {
            logger.error(LogHelper._FUNC_() + e.getMessage());
        }
        return "";
    }

    public static String streamToString(InputStream in){
        StringBuffer buff = new StringBuffer();
        try {
            byte[] b = new byte[4096];
            for (int length; (length = in.read(b)) != -1;) {
                buff.append(new String(b, 0, length));
            }
        } catch (IOException e) {
            buff = buff.delete(0,buff.length());
            e.printStackTrace();
        }
        return buff.toString();
    }

    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(double v1,double v2,int scale){
        if(scale<0){
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }


}
